//
//  LTextField.m
//  CodeForTextField
//
//  Created by 李明明 on 15/10/20.
//  Copyright © 2015年 李明明. All rights reserved.
//

#import "LTextField.h"

@interface LTextField ()
@property (nonatomic, assign) NSInteger cursor;
@end

@implementation LTextField


- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti:) name:UITextFieldTextDidChangeNotification object:nil];
        self.delegate = self;
        [self.spaceArr sortedArrayUsingSelector:@selector(compare:)];

    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti:) name:UITextFieldTextDidChangeNotification object:nil];
        [self.spaceArr sortedArrayUsingSelector:@selector(compare:)];
        self.delegate = self;
    }
    return self;
}
- (void)noti:(NSNotification *)noti
{
    NSString *str = [self formatter];
    self.text = str;
    UITextPosition *from = [self positionFromPosition:self.beginningOfDocument offset:self.cursor];
    UITextPosition *to = [self positionFromPosition:from offset:0];
    [self setSelectedTextRange:[self textRangeFromPosition:from toPosition:to]];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    UITextPosition *from = self.beginningOfDocument; // head of text
    UITextRange *ranges = self.selectedTextRange;  // selected text
    NSInteger count = [self offsetFromPosition:from toPosition:ranges.start];//  cursor position
    self.cursor = count;
    NSString *str = [NSString stringWithFormat:@" %zd ", self.cursor];
    if ([string isEqualToString:@""]) {
        if ([[self getArrContent:2] containsString:str]) {
            self.cursor--;
        }
        self.cursor--;
    }else {
        if ([[self getArrContent:0] containsString:str]) {
            self.cursor++;
        }
        self.cursor++;
    }
    return YES;
}
- (NSString *)formatter
{
    NSMutableString *str = [[self.text stringByReplacingOccurrencesOfString:@" " withString:@""] mutableCopy];
    for (NSInteger i = 0; i < str.length; i++) {
        NSString *string = [NSString stringWithFormat:@" %zd ", i];
        if ([[self getArrContent:0] containsString:string]) {
            [str insertString:@" " atIndex:i];
        }
    }
    return str;
}
- (NSString *)getArrContent:(NSInteger)index
{
    NSMutableString *str = [NSMutableString string];
    for (int i = 0; i < self.spaceArr.count; i++) {
        [str appendFormat:@" %zd ", [self.spaceArr[i] intValue] + i + index];
    }
    return str;
}


@end
